package com.dai.zhenfujin.visitingcard.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.bean.AlumFansListBean;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.view.RoundImageView;
import com.dai.zhenfujin.visitingcard.app.PersonalDetailsActivity;
import com.dai.zhenfujin.visitingcard.app.PersonalDetailsCommentActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.dai.zhenfujin.visitingcard.VisitingcardFragment.context2;

public class VisitingCardAdapter2 extends BaseAdapter {

    private Context context;
    private List<ProListBean.ProListBean2> visitingCardBeanList;
    private List<Boolean> alreadyLikeList = new ArrayList<>();
    private Dialog dialogHead;

    public VisitingCardAdapter2(Context context, List<ProListBean.ProListBean2> visitingCardBean){
        this.context = context;
        this.visitingCardBeanList = visitingCardBean;
    }

    @Override
    public int getCount() {
        return visitingCardBeanList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         VIewHolder holder;
        if(convertView == null){
            holder = new VIewHolder();
            convertView = View.inflate(context,R.layout.visitingcard_item,null);
            holder.tvName = (TextView)convertView.findViewById(R.id.item_name);//姓名
            holder.tvPosition = (TextView)convertView.findViewById(R.id.item_position);//职位
            holder.tvDistance = (TextView)convertView.findViewById(R.id.item_distance);//距离
            holder.tvBloc = (TextView)convertView.findViewById(R.id.item_bloc);//集团

            holder.tvCompany = (TextView)convertView.findViewById(R.id.item_company);//公司
            holder.tvPrice = (TextView)convertView.findViewById(R.id.item_price);//价格
            holder.tvResidence = (TextView)convertView.findViewById(R.id.item_residence);//住宅
            holder.tvSite = (TextView)convertView.findViewById(R.id.item_site);//地址
            holder.ivOne = (CircleImageView) convertView.findViewById(R.id.item_imageview_one);//人的图片
            holder.ivTwo = (RoundImageView)convertView.findViewById(R.id.item_imageview_two);//房子的图片
            holder.tvTypeInfo = convertView.findViewById(R.id.item_word_type);//房子的图片
            holder.llUser = convertView.findViewById(R.id.ll_user);//房子的图片
            holder.rl_pro = convertView.findViewById(R.id.rl_pro);
            holder.view_line = convertView.findViewById(R.id.view_line);
            holder.ll_comment = convertView.findViewById(R.id.ll_comment);
            holder.tv_time = convertView.findViewById(R.id.tv_time);
            holder.ll_lick = convertView.findViewById(R.id.ll_lick);
            holder.iv_lick = convertView.findViewById(R.id.iv_lick);
            holder.ll_share = convertView.findViewById(R.id.ll_share);
            holder.item_user_job = convertView.findViewById(R.id.item_user_job); //主业

            holder.tv_comment_num =  convertView.findViewById(R.id.tv_comment_num);
            holder.tv_like_num =  convertView.findViewById(R.id.tv_like_num);

            convertView.setTag(holder);
        }else {
           holder= (VIewHolder) convertView.getTag();
        }


        ProListBean.ProListBean2 proListBean = visitingCardBeanList.get(position);
        holder.tvName.setText(proListBean.getUser_name());
        holder.tvPosition .setText(proListBean.getUser_duties()); //职务
        holder.tvDistance.setText(UIUtils.getDic(proListBean.getDist()) + "km");
        holder.tvBloc.setText("公司:" + proListBean.getUser_company());
        holder.item_user_job.setText("主业:" + proListBean.getUser_job()); //主业

        holder.tv_comment_num.setText(proListBean.com_num);
        holder.tv_like_num.setText(proListBean.like_num);

        holder.tvCompany.setText(proListBean.getPro_name());
        if (!TextUtils.isEmpty(proListBean.getPro_price())) {
          //  holder.tvPrice.setText("￥" + proListBean.getPro_price() + "元");
           // holder.tvPrice.setVisibility(View.VISIBLE);
        }else {
           // holder.tvPrice.setVisibility(View.INVISIBLE);
        }
        //  holder.tvResidence.setText(proListBean.getResidence());//住宅
      //  holder.tvSite.setText(proListBean.getPro_address());
        holder.tvTypeInfo.setText(proListBean.type_name); //副业
        holder.tv_time.setText(proListBean.create_time.substring(0,proListBean.create_time.length()-2));


        Glide.with(context).load(proListBean.getUser_logo()).into(holder.ivOne);

        if (TextUtils.isEmpty(proListBean.getPro_logo())){
           /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                holder.ivTwo.setBackground(context.getResources().getDrawable(R.mipmap.moen));
            }*/
            holder.rl_pro.setVisibility(View.GONE);
        }else {
            holder.rl_pro.setVisibility(View.VISIBLE);
            Glide.with(context).load(proListBean.getPro_logo()).into(holder.ivTwo);
        }


        holder.llUser.setOnClickListener(v -> {
            Intent intent = new Intent(context,PersonalDetailsActivity.class);
            intent.putExtra("user_id", proListBean.getUser_id());
            intent.putExtra("pro_id", proListBean.getPro_id());
            intent.putExtra("proListBean", proListBean);

            context.startActivity(intent);
        });

        holder.ll_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, PersonalDetailsCommentActivity.class);
                intent.putExtra("proListBean", proListBean);

                context.startActivity(intent);
            }
        });

        alreadyLikeList.add(proListBean.is_like.equals("1"));
        if (alreadyLikeList.get(position)){
            holder.iv_lick.setImageResource(R.mipmap.icon_dianzan2);
            // alreadyLikeList.add(itemList.getIs_like().equals("1")); //0 未点赞
        }else {
            holder.iv_lick.setImageResource(R.mipmap.icon_dianzan);
            //  alreadyLikeList.add(itemList.getIs_like().equals("0")); //已点赞
        }
       /* alreadyLikeList.add(proListBean.is_like.equals("0")); //0 未点赞
        if (alreadyLikeList.get(position)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                holder.iv_lick.setBackground(context.getResources().getDrawable(R.mipmap.icon_dianzan2));
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                holder.iv_lick.setBackground(context.getResources().getDrawable(R.mipmap.icon_dianzan));
            }
        }*/
        holder.ll_lick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> params = new HashMap<>();
                Map<String, String> params2 = new HashMap<>();
                params2.put("msg_id", proListBean.getUser_id());
                //点赞
                if (alreadyLikeList.get(position)){
                    params2.put("type", 2 + ""); //取消点赞
                }else {
                    params2.put("type",1 + ""); //点赞
                }

                params.put("req_bd",  params2);
                HttpClient.post(context, Constants.LIKE, params, new CallBack<AlumFansListBean>() {
                    @Override
                    public void onSuccess(AlumFansListBean resultBean) {
                        // viewHolder.iv_lick.setBackground(context.getResources().getDrawable(R.mipmap.icon_dianzan2));
                        if (alreadyLikeList.get(position)){
                            holder.iv_lick.setImageResource(R.mipmap.icon_dianzan);
                            holder.tv_like_num.setText(Integer.valueOf(holder.tv_like_num.getText().toString()) - 1 + "");
                            alreadyLikeList.set(position,false);
                        }else{
                            holder.iv_lick.setImageResource(R.mipmap.icon_dianzan2);
                            holder.tv_like_num.setText(Integer.valueOf(holder.tv_like_num.getText().toString()) + 1 + "");
                            alreadyLikeList.set(position,true);
                        }
                    }
                });
            }
        });

        holder.ll_share.setOnClickListener(v -> {
            showDialog(proListBean);
        });

        return convertView;
    }

    private void showDialog(ProListBean.ProListBean2 proListBean) {
        setBackgroundAlpha((float) 0.4);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_share_item, null);
        PopupWindow  mPopWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(view);
        // 设置PopupWindow的背景
        mPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setTouchable(true);

        mPopWindow.getContentView().setFocusable(true); // 这个很重要
        mPopWindow.getContentView().setFocusableInTouchMode(true);
        mPopWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mPopWindow.dismiss();

                    return true;
                }
                return false;
            }
        });


        view.findViewById(R.id.ll_weixin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> params = new HashMap<>();
                Map<String, String> params2 = new HashMap<>();
                params2.put("pro_id", proListBean.getPro_id());
                params.put("req_bd", params2);
                HttpClient.post(context, Constants.SHARE, params, new CallBack<ProListBean>() {
                    @Override
                    public void onSuccess(ProListBean resultBean) {
                        String url =  resultBean.share_url;
                        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                        Platform.ShareParams shareParams = new  Platform.ShareParams();
                        shareParams.setTitle(resultBean.share_title);
                        shareParams.setText(resultBean.share_desc);
                        shareParams.setImageUrl(resultBean.share_icon);
                        shareParams.setUrl(url);
                        //分享网页
                        shareParams.setShareType(Platform.SHARE_WEBPAGE);
                        platform.share(shareParams);
                    }
                });
            }
        });
        view.findViewById(R.id.ll_pyquan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> params3 = new HashMap<>();
                Map<String, String> params4 = new HashMap<>();
                params4.put("pro_id", proListBean.getPro_id());
                params3.put("req_bd", params4);
                HttpClient.post(context, Constants.SHARE, params3, new CallBack<ProListBean>() {
                    @Override
                    public void onSuccess(ProListBean resultBean) {
                        String url =  resultBean.share_url;
                        Platform platform = ShareSDK.getPlatform(WechatMoments.NAME);
                        Platform.ShareParams shareParams = new  Platform.ShareParams();
                        shareParams.setTitle(resultBean.share_title);
                        shareParams.setText(resultBean.share_desc);
                        shareParams.setImageUrl(resultBean.share_icon);
                        shareParams.setUrl(url);
                        //分享网页
                        shareParams.setShareType(Platform.SHARE_WEBPAGE);
                        platform.share(shareParams);
                    }
                });
            }
        });
        view.findViewById(R.id.ll_weibo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> params5 = new HashMap<>();
                Map<String, String> params6 = new HashMap<>();
                params6.put("pro_id", proListBean.getPro_id());
                params5.put("req_bd", params6);
                HttpClient.post(context, Constants.SHARE, params5, new CallBack<ProListBean>() {
                    @Override
                    public void onSuccess(ProListBean resultBean) {
                        String url =  resultBean.share_url;
                        Platform platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                        Platform.ShareParams shareParams = new  Platform.ShareParams();
                        shareParams.setTitle(resultBean.share_title);
                        shareParams.setText(resultBean.share_desc);
                        shareParams.setImageUrl(resultBean.share_icon);
                        shareParams.setUrl(url);
                        //分享网页
                        shareParams.setShareType(Platform.SHARE_WEBPAGE);
                        platform.share(shareParams);
                    }
                });
            }
        });

        View rootView = LayoutInflater.from(context).inflate(R.layout.activity_login, null);
        mPopWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1);
            }
        });
    }

    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = context2.getWindow().getAttributes();
        lp.alpha = v;
        context2.getWindow().setAttributes(lp);
    }


    /**
     * 局部更新数据，调用一次getView()方法；Google推荐的做法
     *
     * @param listView 要更新的listview
     * @param position 要更新的位置
     */
    public void notifyDataSetChanged(ListView listView, int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            getView(position, view, listView);
        }
    }


    private class VIewHolder{

        private TextView tvName,tvPosition,tvDistance,tvBloc,tv_time,
                tvCompany,tvPrice,tvResidence,tvSite,tvTypeInfo,item_user_job,tv_comment_num,tv_like_num;
        private RoundImageView ivTwo;
        private View view_line;
        private ImageView iv_lick;
        private CircleImageView ivOne;
        private LinearLayout llUser;
        private RelativeLayout rl_pro;
        private LinearLayout ll_comment,ll_lick,ll_share;
    }
}
